<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Cache;

class CheckToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->isMethod('post')){
            $token = $request->_token_2;
            if ($token) {
                if(time() - substr($token, 0, 10) < 10){ //有些页面小于5s来不及，这里放大到10s
                    return $next($request);
                }
            }
            
            $token  = $request->input('_form_token');
            if ($token){
                $session = app('session');
                $session_token = Cache::get($session->token());
                if ($token!=$session_token){
                    return response()->json(['code'=>0,'msg' => "token error",'message' => "token error"], 401);
                    throw new \RuntimeException('token error.');
                }
                Cache::forget($session->token());
            }else{
                return response()->json(['code'=>0,'msg' => "token error",'message' => "token no set"], 401);
                throw new \RuntimeException('token no set.');
            }
        }
        return $next($request);
    }
}
